package com.tencreat.mq;

import cn.hutool.extra.cglib.CglibUtil;
import com.rabbitmq.client.Channel;
import com.tencreat.common.core.domain.dto.AfterSaleDTO;
import com.tencreat.domain.mall.MallAftersale;
import com.tencreat.domain.mall.dto.CancelAftersaleDTO;
import com.tencreat.service.mall.IMallAftersaleService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.Objects;

/**
 * 取消订单消息的处理者
 * Created by macro on 2018/9/14.
 */
@Component
@RabbitListener(queues = "base-mall.after.sale.back.name")
@Slf4j
public class ConfirmAfterSaleBackConsumer {
    private static Logger LOGGER =LoggerFactory.getLogger(ConfirmAfterSaleBackConsumer.class);

    @Autowired
    private IMallAftersaleService mallAftersaleService;

    @RabbitHandler(isDefault=true)
    public void handle(Message message, Channel channel) throws Exception{
        log.info("进入买家未处理自动取消队列--------------------------------------");
        ByteArrayInputStream byteInt = new ByteArrayInputStream(message.getBody());
        ObjectInputStream objInt = new ObjectInputStream(byteInt);
        AfterSaleDTO orderVO = (AfterSaleDTO) objInt.readObject();

        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        //信息为空,丢弃该信息
        if (Objects.isNull(orderVO)) {
            log.info("消息为空,手动丢弃该消息....");
            channel.basicNack(deliveryTag, false, false);
            return;
        }
        int count1 = mallAftersaleService.lambdaQuery()
                .eq(MallAftersale::getOrderGoodsId, orderVO.getOrderGoodsId())
                .eq(MallAftersale::getId, orderVO.getId())
                .isNotNull(MallAftersale::getShipSn)
                .count();
        if (count1 > 0){
            channel.basicAck(deliveryTag, false);
        }else {
            LOGGER.info("自动取消售后----:{}",orderVO.getOrderGoodsId());
            CancelAftersaleDTO mallAftersale = new CancelAftersaleDTO();
            CglibUtil.copy(orderVO,mallAftersale);
            log.info("对象的值-----:{}",mallAftersale.getOrderGoodsId());
            int count = mallAftersaleService.cancelAfterSale(mallAftersale);
            if (count > 0 ){
                channel.basicAck(deliveryTag, false);
            }
        }
    }
}
